package com.iotstudio.embeddedcloudplatform.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iotstudio.embeddedcloudplatform.POJO.DO.*;
import com.iotstudio.embeddedcloudplatform.POJO.VO.ResultVO;
import com.iotstudio.embeddedcloudplatform.config.RedisConfig;
import com.iotstudio.embeddedcloudplatform.constants.CommonConstants;
import com.iotstudio.embeddedcloudplatform.constants.HttpParamKey;
import com.iotstudio.embeddedcloudplatform.constants.PermissionConstants;
import com.iotstudio.embeddedcloudplatform.constants.ResourceConstants;
import com.iotstudio.embeddedcloudplatform.dao.SensorMapper;
import com.iotstudio.embeddedcloudplatform.enums.IdentifyTypeEnum;
import com.iotstudio.embeddedcloudplatform.service.SensorService;
import com.iotstudio.embeddedcloudplatform.service.UserService;
import com.iotstudio.embeddedcloudplatform.util.web.CookieUtil;
import com.iotstudio.embeddedcloudplatform.util.web.ResultVOUtil;
import com.sun.org.apache.regexp.internal.RE;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户操作
 * @author BeFondOfTaro
 * Created at 12:12 2018/1/20
 */
@RestController
@Api(tags = "用户操作")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private SensorService sensorService;
    /**
     * 登录
     * @param identifyType 身份认证方式
     * @param identifier 身份标识(用户名等)
     * @param credential 凭证(密码等)
     * @return
     */
    @ApiOperation(value = "用户登录",notes = "用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "identifyType", value = "身份认证方式，默认为用户名密码登录", defaultValue = "0",required = true),
            @ApiImplicitParam(name = "identifier",value = "身份标识(用户名等)",required = true),
            @ApiImplicitParam(name = "credential",value = "凭证(密码等)",required = true)
    })
    @GetMapping(CommonConstants.PUB_PREFIX + "/login")
    public ModelAndView login(
            @RequestParam(value = "identifyType",defaultValue = "0") Integer identifyType,
            @RequestParam("identifier") String identifier,
            HttpServletResponse response,
            @RequestParam("credential") String credential){
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("redirect:/static/index.html");
            ResultVO resultVO =userService.login(response,identifyType,identifier,credential);

            System.out.println(resultVO.getMsg());
        return modelAndView;
    }


    /**
     * 用户注册(仅通过管理员操作)
     * @param realName 姓名
     * @param username 用户名
     * @param password 密码
     * @param roleId 角色
     * @return
     */
    @PostMapping(CommonConstants.PUB_PREFIX + "/" + ResourceConstants.USER)
    @ApiOperation(value = "用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "realName", value = "姓名", required = true),
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "password",value = "密码",required = true,defaultValue = "123456"),
            @ApiImplicitParam(name = "roleId",value = "角色id,默认为管理员",required = true,defaultValue = "1")
    })
    public ResultVO register(
            @RequestParam("realName") String realName,
            @RequestParam("username") String username,
            @RequestParam(value = "password",defaultValue = "123456") String password,
            @RequestParam(value = "roleId",defaultValue = "1") String roleId
    ){
        User user = new User(username,realName,"","","");
        UserAuth userAuth = new UserAuth(
                IdentifyTypeEnum.USERNAME.getCode(),
                username,
                password
                );
        return userService.register(user,userAuth,roleId);
    }

    /**
     * 注销登录
     * @return
     */
    @ApiOperation(value = "用户注销登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = HttpParamKey.CLIENT_DIGEST,value = "令牌",paramType = "header",required = true),
    })
    @DeleteMapping(CommonConstants.NONPUBLIC_PREFIX + "/logout")
    public ResultVO logout(){
        System.out.println("成功");
        return userService.logout();
    }

    @ApiOperation(value = "删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = HttpParamKey.CLIENT_DIGEST,value = "令牌",paramType = "header",required = true),
    })
    @DeleteMapping(CommonConstants.NONPUBLIC_PREFIX + "/" + ResourceConstants.USER)
    @RequiresPermissions(ResourceConstants.USER + PermissionConstants.DELETE)
    public ResultVO deleteUser(String userId){
        userService.deleteUser(userId);
        return ResultVOUtil.success();
    }

    /**
     * 编辑用户信息
     * @return
     */
    @ApiOperation(value = "编辑用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = HttpParamKey.CLIENT_DIGEST,value = "令牌",paramType = "header",required = true),
    })
    @GetMapping(CommonConstants.NONPUBLIC_PREFIX + "/userEdit")
    public User editUser(){
        return userService.editUser();
    }
    /**
     * 根据用户id得到传感器名称
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = HttpParamKey.CLIENT_DIGEST,value = "令牌",paramType = "header",required = true),
    })
    @PostMapping(CommonConstants.PUB_PREFIX + "/getSensorName")
    public JSONArray getSensorName(
            HttpServletRequest request
    ){
        String userId = CookieUtil.getCookieValueByName(request,"userId");
        List<String> list = userService.getSensorId(userId);
        List<Sensor> list1 = new ArrayList();
        for (int i =0;i<list.size();i++){
            Sensor sensor=sensorService.getSensor(list.get(i));
            System.out.println(sensor);
            list1.add(sensor);
        }
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        JSONObject jsonObject2 = new JSONObject();
        jsonObject.put("accessPath","");
        jsonObject.put("checked",false);
        jsonObject.put("delFlag",0);
        jsonObject.put("parentID",1);
        jsonObject.put("resourceCode","");
        jsonObject.put("resourceDesc","");
        jsonObject.put("resourceGrade",2);
        jsonObject.put("resourceID",3);
        jsonObject.put("resourceName","我的设备");
        jsonObject.put("resourceOrder",0);
        jsonObject.put("resourceType","");
        jsonArray.add(jsonObject);
        jsonObject1.put("accessPath","add.html");
        jsonObject1.put("checked",false);
        jsonObject1.put("delFlag",0);
        jsonObject1.put("parentID",1);
        jsonObject1.put("resourceCode","");
        jsonObject1.put("resourceDesc","");
        jsonObject1.put("resourceGrade",2);
        jsonObject1.put("resourceID",2);
        jsonObject1.put("resourceName","添加设备");
        jsonObject1.put("resourceOrder",0);
        jsonObject1.put("resourceType","");
        jsonArray.add(jsonObject1);
        jsonObject2.put("accessPath","#");
        jsonObject2.put("checked",false);
        jsonObject2.put("delFlag",0);
        jsonObject2.put("parentID",1);
        jsonObject2.put("resourceCode","");
        jsonObject2.put("resourceDesc","");
        jsonObject2.put("resourceGrade",2);
        jsonObject2.put("resourceID",4);
        jsonObject2.put("resourceName","用户信息");
        jsonObject2.put("resourceOrder",0);
        jsonObject2.put("resourceType","");
        jsonArray.add(jsonObject2);
        for (int j =0;j<list1.size();j++){
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.put("accessPath","../v1/pub/getSensorId?sensorId="+list1.get(j).getId());
            jsonObject3.put("checked",false);
            jsonObject3.put("delFlag",0);
            jsonObject3.put("parentID",3);
            jsonObject3.put("resourceCode","");
            jsonObject3.put("resourceDesc","");
            jsonObject3.put("resourceGrade",2);
            jsonObject3.put("resourceID",j+5);
            jsonObject3.put("resourceName",list1.get(j).getName());
            jsonObject3.put("resourceOrder",0);
            jsonObject3.put("resourceType","");
            jsonArray.add(jsonObject3);
        }
        return jsonArray;
    }
    @ApiOperation(value = "编辑用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = HttpParamKey.CLIENT_DIGEST,value = "令牌",paramType = "header",required = true),
    })
    @GetMapping(CommonConstants.PUB_PREFIX + "/getSensorId")
    public ModelAndView getSensorId(HttpServletResponse response,String sensorId){
        CookieUtil.addCookie(response,"sensorId",sensorId);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/static/chuanganqi.html");
        return modelAndView;
    }
}
